package commom

import (
	"os"
	"os/exec"
	"runtime"
	"strings"
)

//window 执行cmd
func runInWindows(cmd string) (string, error) {
	result, err := exec.Command("cmd", "/c", cmd).Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(result)), err
}

//自动识别系统
func RunCommand(cmd string) (string, error) {
	if runtime.GOOS == "windows" {
		return runInWindows(cmd)
	} else {
		return runInLinux(cmd)
	}
}

func runInLinux(cmd string) (string, error) {
	result, err := exec.Command("/bin/sh", "-c", cmd).Output()

	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(result)), err
}

//根据进程名判断进程是否运行
func CheckProRunning(serverName string) (bool, error) {
	a := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $10}'`
	pid, err := RunCommand(a)
	if err != nil {
		return false, err
	}
	return pid != "", nil
}

//本系统的PID
func CheckLocalRuning(serverName string) bool {
	a := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	cpid := os.Getpid()
	pid, err := RunCommand(a)
	if err != nil {
		return false
	}
	cpst_str := Strval(cpid)
	pid = strings.Replace(pid, cpst_str, "", -1)
	return pid != ""
}

//根据进程名称获取进程ID
func GetPid(serverName string) (string, error) {
	a := `ps ux | awk '/` + serverName + `/ && !/awk/ {print $2}'`
	pid, err := RunCommand(a)
	return pid, err
}
